package com.hxzy.controller.admin.merchandiser;

import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.resp.PageResp;
import com.hxzy.common.vo.resp.R;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.controller.admin.merchandiser.req.MerchandiserReq;
import com.hxzy.controller.admin.merchandiser.req.ProcessReq;
import com.hxzy.controller.admin.merchandiser.resp.MerchandiserResp;
import com.hxzy.entity.Merchandiser;
import com.hxzy.service.MerchandiserService;
import com.hxzy.util.sms.Sms1455683;
import com.hxzy.util.sms.Sms1770265;
import com.hxzy.util.sms.SmsRequestReq;
import com.hxzy.util.sms.SmsTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @Desc 描述
 * @Author: admin
 * @Date: 2023/07/11/9:08
 */
@Api(tags = "管理后台-商家列表")
@RestController
@RequestMapping(value = "/api/merchandiser")
public class MerchandiserController {

    @Autowired
    private MerchandiserService merchandiserService;

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R<PageResp<MerchandiserResp>> search(@Valid MerchandiserReq req){
        AdminLoginResp  adminLoginResp= WaimaiThreadLocal.getCurrent();
        //商家
        if(adminLoginResp.getType()==2){
            req.setTenantId(adminLoginResp.getId());
        }

        PageInfo<MerchandiserResp> pageInfo=this.merchandiserService.search(req);

        PageResp<MerchandiserResp> resp=new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setRows(pageInfo.getList());
        return R.okHasData(resp);
    }


    @ApiOperation(value = "审核")
    @PutMapping(value = "/process")
    public R process(@RequestBody @Valid ProcessReq req){

        Merchandiser db = this.merchandiserService.getById(req.getTenantId());
        if(Objects.isNull(db)){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        //如果商家状态不是0，就不能进行审核
        if(!db.getStatus().equals("0")){
            return R.build(AckCode.ENTERPRISE_STATUS_ERROR);
        }

        boolean result=this.merchandiserService.process(req);

        if(result){
            //发送短信 (简单工厂方法模式)
            SmsRequestReq sms=null;
            if(req.getStatus().equals("1")){
                sms = new Sms1455683(db.getLoginName(), db.getName());
            }else {
                sms = new Sms1770265(db.getLoginName(), req.getDescription());
            }
            SmsTemplate smsTemplate=new SmsTemplate();
            smsTemplate.sendSms(sms);
        }

        return result?R.ok():R.build(AckCode.DATABASE_ERROR);
    }

}
